/**
 * 辅助函数
 * 提供应用中通用的工具函数
 */

/**
 * 生成分页信息
 * @param {number} total - 总记录数
 * @param {number} page - 当前页码
 * @param {number} limit - 每页条数
 * @returns {Object} 分页信息
 */
const getPagination = (total, page, limit) => {
  const currentPage = parseInt(page) || 1;
  const pageSize = parseInt(limit) || 10;
  const totalPages = Math.ceil(total / pageSize);
  
  return {
    total,
    current_page: currentPage,
    page_size: pageSize,
    total_pages: totalPages,
    has_more: currentPage < totalPages
  };
};

/**
 * 从对象中提取指定字段
 * @param {Object} obj - 源对象
 * @param {Array} fields - 要提取的字段数组
 * @returns {Object} 新对象
 */
const pickFields = (obj, fields) => {
  return fields.reduce((result, field) => {
    if (obj && obj[field] !== undefined) {
      result[field] = obj[field];
    }
    return result;
  }, {});
};

/**
 * 格式化日期
 * @param {Date|string} date - 日期对象或字符串
 * @param {string} format - 格式化模板，默认为 'YYYY-MM-DD'
 * @returns {string} 格式化后的日期字符串
 */
const formatDate = (date, format = 'YYYY-MM-DD') => {
  const d = new Date(date);
  
  if (isNaN(d.getTime())) {
    return '';
  }
  
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds);
};

/**
 * 将金额格式化为货币字符串
 * @param {number} amount - 金额
 * @param {string} currency - 货币代码，默认为 'CNY'
 * @param {string} locale - 地区，默认为 'zh-CN'
 * @returns {string} 格式化后的金额字符串
 */
const formatCurrency = (amount, currency = 'CNY', locale = 'zh-CN') => {
  return new Intl.NumberFormat(locale, {
    style: 'currency',
    currency,
    minimumFractionDigits: 2
  }).format(amount);
};

/**
 * 生成随机颜色
 * @param {string} format - 颜色格式 ('hex' | 'rgb' | 'hsl')
 * @returns {string} 颜色字符串
 */
const randomColor = (format = 'hex') => {
  switch (format) {
    case 'rgb':
      const r = Math.floor(Math.random() * 256);
      const g = Math.floor(Math.random() * 256);
      const b = Math.floor(Math.random() * 256);
      return `rgb(${r}, ${g}, ${b})`;
    
    case 'hsl':
      const h = Math.floor(Math.random() * 360);
      const s = Math.floor(Math.random() * 100);
      const l = Math.floor(Math.random() * 60) + 30; // 30-90% 亮度避免太暗或太亮
      return `hsl(${h}, ${s}%, ${l}%)`;
    
    default: // hex
      const hex = Math.floor(Math.random() * 16777215).toString(16);
      return `#${hex.padStart(6, '0')}`;
  }
};

module.exports = {
  getPagination,
  pickFields,
  formatDate,
  formatCurrency,
  randomColor
}; 